package com.example.demo.main.rabbitmq.exchange.direct.hello;

import com.example.demo.main.rabbitmq.utils.RabbitmqConnectionUtil;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * @author xieluoyin
 *  2018/8/5 19:26
 */
public class Receive {
    private final static String QUEUE_NAME = "testHello";

    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = RabbitmqConnectionUtil.getConnection();
        //创建通道
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. ");

        /*
         * 告诉服务器我们需要那个管道的消息，如果管道中有消息，就会执行回调函数handleDelivery
         */
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println(" [Consumer] Received '" + message + "'");
            }
        };

        /*
         * basicConsume方法参数：
         *  第一个参数是Consumer绑定的队列名
         *  第二个参数是自动确认标志，如果为true，表示Consumer接受到消息后，会自动发确认消息(Ack消息)给消息队列，消息队列会将这条消息从消息队列里删除
         *  第三个参数就是Consumer对象，用于处理接收到的消息
         */
        channel.basicConsume(QUEUE_NAME, true, consumer);

        //channel.close();
        //connection.close();


    }
}
